require("./app/app.component.less");
import * as $ from "jquery";
// import * as moment from "moment";
// import { Observable } from "rxjs/Observable";
// import { Subject } from "rxjs/Subject";
import { BASEURL } from "shared";
// import "./shared/rxjs-operators";
// import { DB_NAME, DB_ARTICLE_STORE_NAME } from "utils";

// let setGlobalVars = require("indexeddbshim");

// setGlobalVars();

export const DB_NAME = "CaimiDB";
export const DB_ARTICLE_STORE_NAME = "Articles";


function search() {
  let reg = /[^?&=]+?(?=\=|\?|\&|$)/g;
  return location.
    search.
    match(reg).
    reduce(
    (pre, cur, curIndex, array) =>
      curIndex % 2 === 0 ?
        Object.assign({}, pre, { [cur]: array[curIndex + 1] }) :
        pre,
    {});
}

$(function (global) {
  let db: IDBDatabase;
  let params = search();
  // let workflow =
  //   new Subject().switchMap(params => );

  // console.debug("Params: ", params);
  // console.debug("Observable: ", Observable);

  // // 检测当前是否存在IndexedDB，不存在，Ajax取回，显示
  // // 检测当前ID是否存在于IndexedDB中；存在，取出显示
  // // 不存在，Ajax取回，存入IndexedDB；显示
  // if (global.indexedDB) {
  //   let req: IDBOpenDBRequest = indexedDB.open(DB_NAME, 2);
  //   let newDatabaseSource = Observable.fromEvent(req, "upgradeneeded").switchMap((e: Event) => {
  //     let db: IDBDatabase = (e["target"] as IDBRequest).result;
  //     console.debug("DB Upgrade: ", db);
  //     let objectStore = db.createObjectStore(DB_ARTICLE_STORE_NAME, {
  //       keyPath: "id"
  //     }).createIndex("stock_code", "stock_code", { unique: false });

  //     return Observable.fromEvent(e["target"]["transaction"], "success").map(() => db);
  //   }).publishReplay();
  //   newDatabaseSource.connect();

  //   let openDatabaseSource = Observable.fromEvent(req, "success").map((e: Event) => {
  //     console.debug("DB SUccess: ", e);
  //     let db: IDBDatabase = (e["target"] as IDBRequest).result;
  //     return db;
  //   })


  //   let dbSource = Observable.merge(newDatabaseSource, openDatabaseSource).publishReplay();
  //   dbSource.connect();
  //   dbSource.subscribe((dbSource: IDBDatabase) => {
  //     db = dbSource;
  //   });
  //   let dataCachedSource =
  //     dbSource.
  //       switchMap(db =>
  //         Observable.fromEvent
  //           (db.
  //             transaction(DB_ARTICLE_STORE_NAME, "readonly").
  //             objectStore(DB_ARTICLE_STORE_NAME).
  //             get(params["id"]), "success")).
  //       map(e => e["target"]["result"]).publishReplay();
  //   dataCachedSource.connect();
  //   let dateFreshSource =
  //     dbSource.
  //       switchMap(db =>
  //         Observable.merge(
  //           Observable.fromEvent(db.
  //             transaction(DB_ARTICLE_STORE_NAME, "readonly").
  //             objectStore(DB_ARTICLE_STORE_NAME).
  //             get(params["id"]), "error"),
  //           dataCachedSource.
  //             filter(e => !e))
  //       ).
  //       switchMap(() => updateEntryFromAjax(params["id"])).publishReplay();
  //   dateFreshSource.connect();
  //   dateFreshSource.subscribe((res: any[]) => {
  //     let transaction: IDBTransaction = db.transaction(DB_ARTICLE_STORE_NAME, "readwrite");
  //     // (res as any[]).forEach(entry => {
  //       transaction.objectStore(DB_ARTICLE_STORE_NAME).put(res);
  //     // })
  //   });

  //   Observable.merge(
  //     dataCachedSource.filter(e => e !== undefined),
  //     dateFreshSource
  //     // dateFreshSource.map((res: any[]) => res.filter(entry => entry.id === params["id"]).reduce((init, last) => last, {}))
  //   ).subscribe(entry => updateViewFrom(entry))
  // } else {
    let type = 'f10news'
    if (params['type']===type) {
      updateEntryFromAjaxF10(params["id"])
    } else {
      updateEntryFromAjax(params["id"]);
    }
      // subscribe((res: any) =>
      //   updateViewFrom(
      //     res
      //     // res.filter(entry => entry.id === params["id"]).reduce((init, last) => last, {})
      //   )
      // );
  // }


  function updateEntryFromAjax(id: string){
    // return Observable.create(observer => {
      $.get(
        `${BASEURL}/stock/${params["symbol"]}/${params["type"]}/${id}`,
        res => {
          console.debug("From Ajax:", res);
          updateViewFrom(res);
          // observer.complete(res);
        }
      );
      // $(document).ajaxError(e => observer.error(e));
    // });
  }

  // f10 news
  function updateEntryFromAjaxF10(id: string){
      // todo ===>>>> 测试结束应该删除测试代码
      // 非正式环境时用于跨域请求测试
      // if (BASEURL.indexOf('hrhg') < 0) {
      //   global.fetch && global.fetch(`${BASEURL}/stock/newinfo/news/${id}`,{
      //     method: 'GET',
      //     mode: 'cors'
      //   }).then(function (res) {
      //     return res.json()
      //   }).then(function(res: any){
      //     let news = {
      //       id: res.id,
      //       title: res.infoTitle,
      //       media: res.media,
      //       date: res.infoPublDate.slice(0, res.infoPublDate.indexOf(' ')),
      //       content: res.content,
      //       stock_code: '',
      //       conclusion: '',
      //       publ_date: '',
      //       org_name: ''
      //     }
      //     updateViewFrom(news);
      //   })
      //   return
      // }
      $.get(
        `${BASEURL}/stock/newinfo/news/${id}`,
        res => {
          let news = {
            id: res.id,
            title: res.infoTitle,
            media: res.media,
            date: res.infoPublDate.slice(0, res.infoPublDate.indexOf(' ')),
            content: res.content,
            stock_code: '',
            conclusion: '',
            publ_date: '',
            org_name: ''
          }
          updateViewFrom(news);
        }
      );
  }

  function updateViewFrom(news: { id; content; media, stock_code, title, date, conclusion, publ_date, org_name }) {
    console.debug("News: ", news);
    $(".title").text(news.title);
    $(".meta-date").text(news.date || news.publ_date);
    $(".meta-media-link").text(news.media || news.org_name);
    // $(".meta-pv-amount").text()
    (getContentHtml(news.content || news.conclusion) as any[]).
      forEach(elem =>
        $(".article-content").append(elem));
  }

  function parseContent(text: string): string[] {
    if (!text) return [text];
    return text.replace(/<br\/?>/g, "").split(/\\n{1,}|\s{2,}/).filter(s => !!s);
  }

  function getContentHtml(text: string) {
    return parseContent(text).map(para => $("<p class='article-para'>").text(para));
  }


} (window));